/*
 * Copyright (c) 2016 Qunar.com. All Rights Reserved.
 */
package com.guoyu.project.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.guoyu.project.common.constant.Constants;
import com.guoyu.project.common.context.ContextKey;
import com.guoyu.project.common.context.CurrentContext;

/**
 * 该过滤器最后会清除上下文信息
 * 
 * @author: libo Date: 16-3-3 Time: 下午6:26
 * @version: \$Id$
 **/
public class AccessFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(AccessFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("access filter start!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String token = httpRequest.getHeader(Constants.ACCESS_TOKEN);
            CurrentContext.setToCurrent(ContextKey.TOKEN_KEY, token);
            chain.doFilter(request, response);
        } finally {
            // 清除上下文
            CurrentContext.getCurrent().close();
        }
    }

    @Override
    public void destroy() {
        logger.info("access filter destroy!");
    }
}
